<template>
  <s-layout :title="product.name || '产品详情'">
    <view class="detail-container">
      <scroll-view scroll-y class="content-scroll">
        <!-- 商品主图 -->
        <image class="product-main-image" :src="product.image" mode="widthFix" />

        <!-- 商品信息 -->
        <view class="product-info-card">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-desc">{{ product.description }}</view>
          <view class="product-price">¥{{ currentPrice }}</view>
        </view>

        <!-- 套餐包含商品 -->
        <view class="included-products" v-if="product.requiredProducts && product.requiredProducts.length > 0">
          <view class="section-title">套餐包含</view>
          <view class="product-item" v-for="(item, index) in product.requiredProducts" :key="index">
            <image class="product-item-img" :src="item.img || item.product_img" mode="aspectFill" />
            <view class="product-item-info">
              <view class="product-item-name">{{ item.name || item.product_name }}</view>
              <view class="product-item-amount">x{{ item.amount || 1 }}</view>
            </view>
          </view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-card" v-if="product.specs && product.specs.length > 0">
          <view class="stock-tip" v-if="hasDisabledOptions">
            ℹ️ 灰色划线选项暂无库存
          </view>
          <view class="spec-group" v-for="spec in product.specs" :key="spec.id">
            <view class="spec-group-header">
              <view class="spec-group-name">
                {{ spec.name }}
                <text class="disabled-count" v-if="getDisabledCount(spec) > 0">
                  ({{ getAvailableCount(spec) }} 个可选)
                </text>
              </view>
            </view>
            <view class="spec-options">
              <button
                class="spec-option"
                v-for="option in spec.options"
                :key="option.id"
                :class="{ 
                  active: isOptionSelected(spec, option),
                  disabled: isOptionDisabled(spec, option)
                }"
                :disabled="isOptionDisabled(spec, option)"
                @click="selectSpec(spec, option)"
              >
                <view class="option-name">{{ option.name }}</view>
                <view class="option-price" v-if="option.price && option.price > 0">
                  +¥{{ option.price }}
                </view>
              </button>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <view class="price-section">
          <text>¥</text>
          <text class="price-value">{{ currentPrice }}</text>
        </view>
        <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import { 
  getSpecKey, 
  getOptionKey, 
  findOption, 
  safeParseFloat, 
  buildSpecsText, 
  parsePrice,
  parseOriginalPrice,
  buildFullSelectedSpecs,
  stripHtmlTags
} from './common/product-utils.js';

const cateringStore = sheep.$store('catering');

const product = reactive({
  id: 0,
  name: '',
  image: '',
  description: '',
  basePrice: 0,
  originalPrice: 0,
  specs: [],
  requiredProducts: [] // 套餐包含商品
});

const selectedSpecs = reactive({});

onLoad(async (options) => {
  const passedProductId = options.productId || options.id;
  const passedShopId = options.shopId;

  if (!passedProductId) {
    uni.showToast({ title: '缺少商品信息', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }
  
  const store = cateringStore.storeInfo;
  const shopId = passedShopId || (store && (store.shopId || store.id));
  if (!shopId) {
    uni.showToast({ title: '请先选择门店', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }

  console.log('【麦当劳】加载商品详情:', { productId: passedProductId, shopId });
  
  uni.showLoading({ title: '加载中...' });
  try {
    const res = await sheep.$api.catering.getProductDetail(passedProductId, shopId);
    uni.hideLoading();
    
    if ((res.code === 0 || res.code === 200) && res.data) {
      parseProductData(res.data, options);
    } else {
      uni.showToast({ title: '加载商品失败', icon: 'none' });
      setTimeout(() => sheep.$router.back(), 1500);
    }
  } catch (error) {
    uni.hideLoading();
    console.error('【麦当劳】加载商品详情失败:', error);
    uni.showToast({ title: '加载商品失败', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
  }
});

// 解析麦当劳商品数据
function parseProductData(apiData, options) {
  // 基础信息
  product.id = apiData.product_id || apiData.productId || options.productId;
  product.name = apiData.product_name || apiData.productName || options.name || '';
  product.image = apiData.product_img || apiData.productImg || '';
  // ✅ 处理HTML格式的描述
  const rawDesc = apiData.product_description || apiData.productDescription || '';
  product.description = stripHtmlTags(rawDesc);
  product.basePrice = parsePrice(apiData);
  product.originalPrice = parseOriginalPrice(apiData);

  console.log('【麦当劳】售价:', product.basePrice, '原价:', product.originalPrice);

  const details = apiData.details || apiData;
  
  // 套餐包含商品
  product.requiredProducts = details.required || [];
  
  // 可选规格
  if (details.optional) {
    product.specs = details.optional.map(opt => ({
      id: opt.id,
      name: opt.name,
      options: (opt.sku_infos || []).map(sku => ({
        id: sku.id,
        linkId: String(opt.id || ''),  // ✅ 麦当劳：保存规格组id作为linkId
        name: sku.name,
        price: safeParseFloat(sku.price),
        checked: sku.checked || false,
        enabled: sku.enable !== false && sku.disable !== true,
        img: sku.img
      }))
    }));
    
    console.log('【麦当劳】解析后的规格数据:', JSON.stringify(product.specs, null, 2));
  }

  // 初始化默认选中
  initializeDefaultSelection();
}

// 初始化默认选中
function initializeDefaultSelection() {
  product.specs.forEach(spec => {
    if (!spec.options || spec.options.length === 0) return;
    
    const defaultOption = spec.options.find(opt => opt.checked) || spec.options[0];
    selectedSpecs[getSpecKey(spec)] = getOptionKey(defaultOption);
  });
}

// 判断选项是否被选中
function isOptionSelected(spec, option) {
  return selectedSpecs[getSpecKey(spec)] === getOptionKey(option);
}

// 判断选项是否被禁用
function isOptionDisabled(spec, option) {
  return option.enabled === false;
}

// 获取规格组中禁用选项的数量
function getDisabledCount(spec) {
  return spec.options.filter(option => isOptionDisabled(spec, option)).length;
}

// 获取规格组中可用选项的数量
function getAvailableCount(spec) {
  return spec.options.filter(option => !isOptionDisabled(spec, option)).length;
}

// 选择规格
function selectSpec(spec, option) {
  if (isOptionDisabled(spec, option)) return;
  
  const specKey = getSpecKey(spec);
  const optionKey = getOptionKey(option);
  
  selectedSpecs[specKey] = optionKey;
  console.log('【麦当劳】当前已选规格:', JSON.parse(JSON.stringify(selectedSpecs)));
}

// 计算当前价格
const currentPrice = computed(() => {
  let finalPrice = product.basePrice;
  
  // 规格加价
  product.specs.forEach(spec => {
    const specKey = getSpecKey(spec);
    const selectedOptionKey = selectedSpecs[specKey];
    if (!selectedOptionKey) return;
    
    const option = findOption(spec, selectedOptionKey);
    if (option?.price) {
      finalPrice += option.price;
    }
  });
  
  return finalPrice.toFixed(2);
});

// 检查是否有禁用的选项
const hasDisabledOptions = computed(() => {
  return product.specs.some(spec => 
    spec.options.some(option => isOptionDisabled(spec, option))
  );
});

// 加入购物车
function addToCart() {
  // 构建完整的规格对象（包含 id 和 linkId）
  const fullSelectedSpecs = buildFullSelectedSpecs(product.specs, selectedSpecs);
  
  const cartItem = {
    id: product.id,
    name: product.name,
    image: product.image,
    price: parseFloat(currentPrice.value),
    originalPrice: product.originalPrice,
    selectedSpecs: fullSelectedSpecs,
    specsText: buildSpecsText(product.specs, selectedSpecs),
    brandOt: 2,  // ✅ 麦当劳品牌类型
  };

  console.log('【麦当劳】加入购物车 - 售价:', cartItem.price, '原价:', cartItem.originalPrice);
  console.log('【麦当劳】规格数据:', JSON.stringify(fullSelectedSpecs, null, 2));
  cateringStore.addToCart(cartItem);

  uni.showToast({ title: '已加入购物车', icon: 'success' });
  setTimeout(() => sheep.$router.back(), 1000);
}
</script>

<style lang="scss" scoped>
@import './common/product-detail.scss';

// 麦当劳特有样式
.stock-tip {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  color: #1976d2;
  font-size: 24rpx;
  padding: 16rpx 20rpx;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
  line-height: 1.6;
  border-left: 4rpx solid #2196f3;
}

.spec-group-name {
  .disabled-count {
    color: #999;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
}

.spec-option {
  &.disabled {
    background: #f5f5f5 !important;
    color: #ccc !important;
    border: 1rpx solid #e0e0e0 !important;
    opacity: 0.5;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      width: 100%;
      height: 1rpx;
      background: #ccc;
      transform: translateY(-50%);
    }
    
    .option-name::after {
      content: ' (无货)';
      font-size: 20rpx;
      color: #f44336;
    }
  }
}
</style>

